package com.andova.glcamera.pool

import android.os.HandlerThread
import com.andova.egl.EglTaskHThread
import com.andova.egl.EglTextureHThread
import com.andova.egl.HT

class HdrThreadFactory {
    companion object {
        private val sInstance: HdrThreadFactory by lazy { synchronized(HdrThreadFactory::class) { HdrThreadFactory() } }
        fun get(): HdrThreadFactory = sInstance
    }

    private val map = mutableMapOf<@PoolKey String, HandlerThread?>()

    @Synchronized
    fun borrowTask(cameraId: String): HT = borrow(if (HT_NAME_EGL_TASK0.contains(cameraId)) HT_NAME_EGL_TASK0 else HT_NAME_EGL_TASK1) as HT

    @Synchronized
    fun borrowTexture(cameraId: String): HT = borrow(if (HT_NAME_EGL_TEXTURE0.contains(cameraId)) HT_NAME_EGL_TEXTURE0 else HT_NAME_EGL_TEXTURE1) as HT

    @Synchronized
    fun destroyTask(cameraId: String) = destroy(if (HT_NAME_EGL_TASK0.contains(cameraId)) HT_NAME_EGL_TASK0 else HT_NAME_EGL_TASK1)

    @Synchronized
    fun destroyTexture(cameraId: String) = destroy(if (HT_NAME_EGL_TEXTURE0.contains(cameraId)) HT_NAME_EGL_TEXTURE0 else HT_NAME_EGL_TEXTURE1)

    @Synchronized
    fun borrow(@PoolKey key: String): HandlerThread {
        var ht = map[key]
        if (ht == null) {
            ht = when (key) {
                HT_NAME_EGL_TASK0, HT_NAME_EGL_TASK1 -> EglTaskHThread(key).apply { startHandler() }
                HT_NAME_EGL_TEXTURE0, HT_NAME_EGL_TEXTURE1 -> EglTextureHThread(key).apply { startHandler() }
                else -> HandlerThread(key).apply { start() }
            }
            map[key] = ht
        }
        return ht
    }

    @Synchronized
    fun destroy() {
        for (ht in map) destroy(ht.key)
    }

    @Synchronized
    fun destroy(@PoolKey key: String) {
        when (val ht = map[key]) {
            is HT -> ht.quitHandler()
            else -> ht?.quitSafely()
        }
        map[key] = null
    }
}